import Taro, { Component, Config } from '@tarojs/taro'
import { View } from '@tarojs/components'
import './index.less'

interface IProps {
  labels: string[]
  selectedIndex: number
  extClass: string
  onTabChange: () => number
}

interface IState {
  selectedIndex: number
  left: number
}
export default class Index extends Component<IProps, IState> {
  state: IState = {
    selectedIndex: 0,
    left: 51
  }
  static getDerivedStateFromProps(nextProps, prevState) {
    const { selectedIndex } = nextProps
    if (selectedIndex !== prevState.selectedIndex) {
      return {
        selectedIndex: selectedIndex,
        left: selectedIndex * (100 + 19) + 51
      }
    }
    return null
  }
  componentDidMount() {}
  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  tabChange = (index) => {
    this.props.onTabChange(index)
  }

  render() {
    const { labels, extClass } = this.props
    const { left, selectedIndex } = this.state
    return (
      <View className={`tab-bar ${extClass}`}>
        <View className="tabs">
          {labels
            ? labels.map((item, index) => {
                return (
                  <View
                    className={`tab ${index === selectedIndex ? 'active' : ''}`}
                    key={`${index}item`}
                    onClick={this.tabChange.bind(this, index)}
                  >
                    {item}
                  </View>
                )
              })
            : null}
          <View className="tab-bar" style={{ left: `${left}rpx` }}></View>
        </View>
      </View>
    )
  }
}
// Index.defaultProps = {
//   labels: ['话题', '推荐', '关注'],
//   selectedIndex: 1,
//   extClass: '',
//   left: 51
// }
